#-*- coding: UTF-8 -*-

from code.fttrade import *
from code.mysqlhelp import mysqlhelper as mysql

import logging, sys
import pandas as pd

def saveUSAsset():
    trade = fttrade()
    logging.info("start to get us asset:")
    ret, df = trade.getUSAsset()
    

def saveHKAsset(trade):
    ret, df = trade.getHKAsset()
     
    if ret == 0:
        trade.tablename = "hkaccinfo"
        trade.saveToMysql(df,'replace')
        
        trade.tablename = "hkaccinfohis"
        trade.saveToMysql(df,'append')
    else:
        print('error', df)
def test():
        #trade.unlock_ustrade()
        #trade.unlock_hktrade()
        arglen = len(sys.argv)
        
        if arglen <= 1:
            print('请选择保存类型: HK  US')
        elif  arglen == 2:
            type = sys.argv[1]
            
            if type == 'HK':
                saveHKAsset()
            elif type == 'US':
                saveUSAsset()
            else:
                print('暂不支持:'+type)
        elif arglen > 2:
            market = sys.argv[1]
            price = float(sys.argv[2])
            qty = sys.argv[3]
            symbol = sys.argv[4]
            trade = fttrade()
            
            if market == 'HK':
                ret, df = trade.placehkorder( price, qty,market + '.' + symbol, TrdSide.BUY, TrdEnv.SIMULATE)
            else:
                 # res = trade.placeusorder( price, qty,'US.BILI', TrdSide.BUY, TrdEnv.SIMULATE)
                ret, df = trade.placeusorder( price, qty,market+ '.' + symbol, TrdSide.BUY, TrdEnv.SIMULATE)
            
            #ModifyOrderOp.CANCEL
            
            trade.tablename = 'orders'
            trade.saveToMysql(df, 'replace')
            
            print(df)
            
def  get_position():
    trade._init_context('HK')
    mysql = mysql()
    
    #test(trade)
    trade.tablename = 'hkposition'
    df = trade.query_position()
    print(df)
    
    df = pd.DataFrame(df)
    mysql.savedf(df, trade.tablename, 'replace')
    
    
    trade._init_context('US')
    
    #test(trade)
    trade.tablename = 'usposition'
    df = trade.query_position()
    print(df)
    
    df = pd.DataFrame(df)
    mysql.savedf(df, trade.tablename, 'replace')
        
if __name__=='__main__':
    try:
        #while True:
            
            trade = fttrade()
            trade._init_context('HK')
            mysql = mysql()
            
            trade.closecontext()
        
    except Exception as e:
        print('excep:', e)
    print('End')
    logging.info('end.')